package biz.almas.uycnr.crawler.uycnr.channel;

import java.io.IOException;
import java.util.List;

import org.apache.log4j.Logger;

import biz.almas.uycnr.crawler.constant.Constant;
import biz.almas.uycnr.crawler.crawler.UYCNRParser;
import biz.almas.uycnr.crawler.crawler.downloder.UYCNRDownloader;
import biz.almas.uycnr.crawler.dao.ChannelDao;
import biz.almas.uycnr.crawler.entity.Channel;

/**
 * @Description:
 * @Copyright: Copyright (c) 2015 XinJiang Almas Software All Rights Reserved
 * @Company: XinJiang Almas Software
 * @author Ansar786 Nov 24, 2015
 * @version V1.0
 * @history:
 * 
 */
public class ChannelPostService {

	// 定义日志输出对象
	public static Logger logger = Logger.getLogger(ChannelPostService.class);

	private static UYCNRParser parser = new UYCNRParser();

	private long currentTime;

	private int langId ; 
	private String langShortName ;
	
	private String xmlUrl;
	
	/**
	 * @param currentTime
	 */
	public ChannelPostService() {
		super();
		this.currentTime = System.currentTimeMillis();
	}

	public ChannelPostService(int langId, String langShortName, String xmlUrl) {
		super();
		this.currentTime = System.currentTimeMillis();
		this.langId = langId;
		this.langShortName = langShortName;
		this.xmlUrl = xmlUrl;
	}
	
	protected void process() {
		String channelPath = download(xmlUrl, langShortName
				+ currentTime, "index");
		if (channelPath != null && channelPath.length() > 0) {
			if (parser.parseChannel(channelPath, langId)) {
				List<Channel> channels = parser.getChannels();
				store(channels);
			}
		}
	}

	/**
	 * Ansar786 Nov 24, 2015
	 * @param channels
	 */
	private void store(List<Channel> channels) {
		if (channels != null && channels.size() > 0 ) {
			ChannelDao dao = new ChannelDao();
			dao.store(channels,langId);
		}
	}

	/**
	 * 现在并保存栏目XML
	 * Ansar786 Nov 24, 2015
	 * @param xmlUrl
	 * @param path
	 * @param fileName
	 * @return	返回栏目XML保存的路径
	 */
	private String download(String xmlUrl, String path, String fileName) {
		try {
			return UYCNRDownloader.download(xmlUrl, path, fileName);
		} catch (IOException e) {
			logger.error("下载栏目时出错：" + e.toString());
			return null;
		}
	}
	
	public static void main(String[] args) {
		ChannelPostService uycnr = new ChannelPostService(1,"uy_", Constant.CHANNEL_XML_URL);
		uycnr.process();
		ChannelPostService kzcnr = new ChannelPostService(4,"kz_", Constant.CHANNEL_XML_URL_KZ);
		kzcnr.process();
	}
}
